<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">








  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">











  
  
  <link rel="stylesheet" href="/blog/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/blog/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Markowitz’s Mean-Variance Model Derivation in PythonWritten by Jiang Rongrong(2019E8010663001) Interested by “Lecture 3.Quadratic Programing and Portfolio Selection Theory”,I’ve consulted a number of">
<meta property="og:type" content="article">
<meta property="og:title" content="Markowitz&#39;s Mean-Variance Model Derivation in Python">
<meta property="og:url" content="https://hiram711.github.io/2020/01/17/Markowitz-s-Mean-Variance-Model-Derivation-in-Python/index.html">
<meta property="og:site_name" content="几时">
<meta property="og:description" content="Markowitz’s Mean-Variance Model Derivation in PythonWritten by Jiang Rongrong(2019E8010663001) Interested by “Lecture 3.Quadratic Programing and Portfolio Selection Theory”,I’ve consulted a number of">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/pic/item/5bafa40f4bfbfbed801fba1677f0f736afc31f10.jpg">
<meta property="og:image" content="https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/pic/item/5366d0160924ab1880c26d5e3afae6cd7a890b86.jpg">
<meta property="og:image" content="https://hiram711.github.io/blog/images/pasted-10.png">
<meta property="og:image" content="https://hiram711.github.io/blog/images/pasted-9.png">
<meta property="og:image" content="https://hiram711.github.io/blog/images/pasted-8.png">
<meta property="og:updated_time" content="2022-11-22T14:36:48.023Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Markowitz&#39;s Mean-Variance Model Derivation in Python">
<meta name="twitter:description" content="Markowitz’s Mean-Variance Model Derivation in PythonWritten by Jiang Rongrong(2019E8010663001) Interested by “Lecture 3.Quadratic Programing and Portfolio Selection Theory”,I’ve consulted a number of">
<meta name="twitter:image" content="https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/pic/item/5bafa40f4bfbfbed801fba1677f0f736afc31f10.jpg">






  <link rel="canonical" href="https://hiram711.github.io/2020/01/17/Markowitz-s-Mean-Variance-Model-Derivation-in-Python/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Markowitz's Mean-Variance Model Derivation in Python | 几时</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">几时</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    
      
    

    <a href="/blog/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    
      
    

    <a href="/blog/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    
      
    

    <a href="/blog/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签<span class="badge">6</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    
      
    

    <a href="/blog/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类<span class="badge">3</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    
      
    

    <a href="/blog/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档<span class="badge">7</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-commonweal">

    
    
    
      
    

    
      
    

    <a href="/blog/404/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>公益 404</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://hiram711.github.io/blog/2020/01/17/Markowitz-s-Mean-Variance-Model-Derivation-in-Python/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="几时西风">
      <meta itemprop="description" content="但屈指，流年偷换。">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="几时">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Markowitz's Mean-Variance Model Derivation in Python

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2020-01-17 15:04:00" itemprop="dateCreated datePublished" datetime="2020-01-17T15:04:00+08:00">2020-01-17</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2022-11-22 22:36:48" itemprop="dateModified" datetime="2022-11-22T22:36:48+08:00">2022-11-22</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/项目/" itemprop="url" rel="index"><span itemprop="name">项目</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">6.4k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">6 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Markowitz’s-Mean-Variance-Model-Derivation-in-Python"><a href="#Markowitz’s-Mean-Variance-Model-Derivation-in-Python" class="headerlink" title="Markowitz’s Mean-Variance Model Derivation in Python"></a>Markowitz’s Mean-Variance Model Derivation in Python</h1><p>Written by Jiang Rongrong(2019E8010663001)</p>
<p>Interested by “Lecture 3.Quadratic Programing and Portfolio Selection Theory”,I’ve consulted a number of books about Markowitz’s Mean-Variance Model.Therefore,I want to make some discussion about what I’ve learnt and the expeirments when I tried to figure out this model.</p>
<h2 id="Theory-Summary"><a href="#Theory-Summary" class="headerlink" title="Theory Summary"></a>Theory Summary</h2><p>Markowitz made the following assumptions while developing the Mean-Variance Model: </p>
<ol>
<li>Risk of a portfolio is based on the variability of returns from the said portfolio.</li>
<li>An investor is risk averse.</li>
<li>An investor prefers to increase consumption.</li>
<li>The investor’s utility function is concave and increasing, due to his risk aversion and consumption preference.</li>
<li>Analysis is based on single period model of investment.</li>
<li>An investor either maximizes his portfolio return for a given level of risk or maximizes his return for the minimum risk.</li>
<li>An investor is rational in nature.</li>
</ol>
<p>To choose the best portfolio from a number of possible portfolios, each with different return and risk, two separate decisions are to be made, detailed in the below sections: </p>
<ol>
<li>Determination of a set of efficient portfolios.</li>
<li>Selection of the best portfolio out of the efficient set.</li>
</ol>
<p><em>Above quotes from <a href="https://en.wikipedia.org/wiki/Markowitz_model" target="_blank" rel="noopener">wiki</a></em></p>
<p>Based on above assumptions and thoughts,Markowitz establish his Mean-Variance Model as follows:</p>
<p>Formula:</p>
<p><img src="https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/pic/item/5bafa40f4bfbfbed801fba1677f0f736afc31f10.jpg" alt="Formula"></p>
<p>Constraints:</p>
<p><img src="https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/pic/item/5366d0160924ab1880c26d5e3afae6cd7a890b86.jpg" alt="Constraints"></p>
<p>notes:x<sub>i</sub> stands for the weights of asset i,r<sub>i</sub> stands for the return of asset i</p>
<h2 id="Simulations"><a href="#Simulations" class="headerlink" title="Simulations"></a>Simulations</h2><p>In this part ,I will try to use random data to simulate the derivation process of Mean-Variance Model.Thanks for my boyfriend’s leading,I choose python as the main tool.And each line of code is with notes if necessary.</p>
<p>First,initiate and import necessary util packages.</p>
<p>Intro of each util package:</p>
<ul>
<li>numpy and pandas:  Matrix calculate</li>
<li>matplotlib : Data plot</li>
<li>cvxopt : A convex solver</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">import</span> cvxopt <span class="keyword">as</span> opt</span><br><span class="line"><span class="keyword">from</span> cvxopt <span class="keyword">import</span> blas, solvers</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"></span><br><span class="line">np.random.seed(<span class="number">123</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># Turn off progress printing </span></span><br><span class="line">solvers.options[<span class="string">'show_progress'</span>] = <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<p>Assume that there are 4 assets, each with a return series of length 1000. The func numpy.random.randn is used to sample returns from a normal distribution.<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">## NUMBER OF ASSETS</span></span><br><span class="line">n_assets = <span class="number">4</span></span><br><span class="line"></span><br><span class="line"><span class="comment">## NUMBER OF OBSERVATIONS</span></span><br><span class="line">n_obs = <span class="number">1000</span></span><br><span class="line"></span><br><span class="line">return_vec = np.random.randn(n_assets, n_obs)</span><br></pre></td></tr></table></figure></p>
<p>Plot the return series of the assumed 4 assets.<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">plt.plot(return_vec.T, alpha=<span class="number">.4</span>);</span><br><span class="line">plt.xlabel(<span class="string">'time'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'returns'</span>);</span><br></pre></td></tr></table></figure></p>
<p><img src="/blog/images/pasted-10.png" alt="upload successful"></p>
<p>These return series can be used to create a wide range of portfolios. After that random weight vectors and plot those portfolios will be produced. As I want all my capital to be invested, the weights will have to sum to one.<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">rand_weights</span><span class="params">(n)</span>:</span></span><br><span class="line">    <span class="string">''' Produces n random weights that sum to 1 '''</span></span><br><span class="line">    k = np.random.rand(n)</span><br><span class="line">    <span class="keyword">return</span> k / sum(k)</span><br><span class="line"></span><br><span class="line">print(rand_weights(n_assets))</span><br><span class="line">print(rand_weights(n_assets))</span><br></pre></td></tr></table></figure></p>
<p>Next, evaluate how these random portfolios would perform by calculating the mean returns and the volatility (here using standard deviation). I set a filter so that  only  portfolios with a standard deviation of &lt; 2 are ploted for better illustration.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">random_portfolio</span><span class="params">(returns)</span>:</span></span><br><span class="line">    <span class="string">''' </span></span><br><span class="line"><span class="string">    Returns the mean and standard deviation of returns for a random portfolio</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line"></span><br><span class="line">    p = np.asmatrix(np.mean(returns, axis=<span class="number">1</span>))</span><br><span class="line">    w = np.asmatrix(rand_weights(returns.shape[<span class="number">0</span>]))</span><br><span class="line">    C = np.asmatrix(np.cov(returns))</span><br><span class="line">        </span><br><span class="line">    mu = w * p.T</span><br><span class="line">    sigma = np.sqrt(w * C * w.T)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># This recursion reduces outliers to keep plots pretty</span></span><br><span class="line">    <span class="keyword">if</span> sigma &gt; <span class="number">2</span>:</span><br><span class="line">        <span class="keyword">return</span> random_portfolio(returns)</span><br><span class="line">    <span class="keyword">return</span> mu, sigma</span><br></pre></td></tr></table></figure>
<p>Calculate the return using</p>
<p align="center">R=p<sup>T</sup>w</p>

<p>where R is the expected return, p<sup>T</sup> is the transpose of the vector for the mean returns for each time series and w is the weight vector of the portfolio. p is a N*1 column vector, so p<sup>T</sup> turns is a 1*N row vector which can be multiplied with the  weight (column) vector w to give a scalar result.  </p>
<p>Next, Calculate the standard deviation</p>
<p align="center">sigma=sqrt(w<sup>T</sup>Cw)</p>

<p>where C is the N*N  covariance matrix of the returns.</p>
<p>Generate the mean returns and volatility for 500 random portfolios and plot them:<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">n_portfolios = <span class="number">500</span></span><br><span class="line">means, stds = np.column_stack([</span><br><span class="line">    random_portfolio(return_vec) </span><br><span class="line">    <span class="keyword">for</span> _ <span class="keyword">in</span> range(n_portfolios)</span><br><span class="line">])</span><br><span class="line"></span><br><span class="line">plt.plot(stds, means, <span class="string">'o'</span>, markersize=<span class="number">5</span>)</span><br><span class="line">plt.xlabel(<span class="string">'std'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'mean'</span>)</span><br><span class="line">plt.title(<span class="string">'Mean and standard deviation of returns of randomly generated portfolios'</span>);</span><br></pre></td></tr></table></figure></p>
<p><img src="/blog/images/pasted-9.png" alt="upload successful"></p>
<p>By observing the picture it can be figured out that they form a characteristic parabolic shape called the “Markowitz Bullet” whose upper boundary is called the “efficient frontier”, where investors can have the lowest variance for a given expected return.</p>
<p>Now  the efficient frontier in Markowitz-style can be calculated. This is done by minimizing</p>
<p>w<sup>T</sup>Cw</p>
<p>for fixed expected portfolio return R<sup>T</sup>w while keeping the sum of all the weights equal to 1:</p>
<p>sum(w<sub>i</sub>)=1 (i=1,2,3…n)</p>
<p>Here I parametrically run through R<sup>T</sup>w=miu and find the minimum variance for different miu‘s.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">optimal_portfolio</span><span class="params">(returns)</span>:</span></span><br><span class="line">    n = len(returns)</span><br><span class="line">    returns = np.asmatrix(returns)</span><br><span class="line">    </span><br><span class="line">    N = <span class="number">100</span></span><br><span class="line">    mus = [<span class="number">10</span>**(<span class="number">5.0</span> * t/N - <span class="number">1.0</span>) <span class="keyword">for</span> t <span class="keyword">in</span> range(N)]</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># Convert to cvxopt matrices</span></span><br><span class="line">    S = opt.matrix(np.cov(returns))</span><br><span class="line">    pbar = opt.matrix(np.mean(returns, axis=<span class="number">1</span>))</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># Create constraint matrices</span></span><br><span class="line">    G = -opt.matrix(np.eye(n))   <span class="comment"># negative n x n identity matrix</span></span><br><span class="line">    h = opt.matrix(<span class="number">0.0</span>, (n ,<span class="number">1</span>))</span><br><span class="line">    A = opt.matrix(<span class="number">1.0</span>, (<span class="number">1</span>, n))</span><br><span class="line">    b = opt.matrix(<span class="number">1.0</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># Calculate efficient frontier weights using quadratic programming</span></span><br><span class="line">    portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)[<span class="string">'x'</span>] </span><br><span class="line">                  <span class="keyword">for</span> mu <span class="keyword">in</span> mus]</span><br><span class="line">    <span class="comment">## CALCULATE RISKS AND RETURNS FOR FRONTIER</span></span><br><span class="line">    returns = [blas.dot(pbar, x) <span class="keyword">for</span> x <span class="keyword">in</span> portfolios]</span><br><span class="line">    risks = [np.sqrt(blas.dot(x, S*x)) <span class="keyword">for</span> x <span class="keyword">in</span> portfolios]</span><br><span class="line">    <span class="comment">## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE</span></span><br><span class="line">    m1 = np.polyfit(returns, risks, <span class="number">2</span>)</span><br><span class="line">    x1 = np.sqrt(m1[<span class="number">2</span>] / m1[<span class="number">0</span>])</span><br><span class="line">    <span class="comment"># CALCULATE THE OPTIMAL PORTFOLIO</span></span><br><span class="line">    wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)[<span class="string">'x'</span>]</span><br><span class="line">    <span class="keyword">return</span> np.asarray(wt), returns, risks</span><br><span class="line"></span><br><span class="line">weights, returns, risks = optimal_portfolio(return_vec)</span><br><span class="line"></span><br><span class="line">plt.plot(stds, means, <span class="string">'o'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'mean'</span>)</span><br><span class="line">plt.xlabel(<span class="string">'std'</span>)</span><br><span class="line">plt.plot(risks, returns, <span class="string">'y-o'</span>)</span><br><span class="line">print(weights)</span><br></pre></td></tr></table></figure>
<p><img src="/blog/images/pasted-8.png" alt="upload successful"></p>
<p>In yellow is the optimal portfolios for each of the desired returns (i.e. the mus). In addition, the weights for one optimal portfolio are also calculated.</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/09/13/码农正确装逼姿势——书法篇/" rel="next" title="码农正确装逼姿势——书法篇">
                <i class="fa fa-chevron-left"></i> 码农正确装逼姿势——书法篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2020/11/16/Machine-Learning-基本概念/" rel="prev" title="Machine Learning 基本概念">
                Machine Learning 基本概念 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">几时西风</p>
              <div class="site-description motion-element" itemprop="description">但屈指，流年偷换。</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/blog/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/blog/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://github.com/Hiram711" title="GitHub &rarr; https://github.com/Hiram711" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="mailto:371721772@qq.com" title="E-Mail &rarr; mailto:371721772@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Markowitz’s-Mean-Variance-Model-Derivation-in-Python"><span class="nav-number">1.</span> <span class="nav-text">Markowitz’s Mean-Variance Model Derivation in Python</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Theory-Summary"><span class="nav-number">1.1.</span> <span class="nav-text">Theory Summary</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Simulations"><span class="nav-number">1.2.</span> <span class="nav-text">Simulations</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">几时西风</span>

  

  
</div>









        








        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  <script src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/blog/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/blog/js/src/utils.js?v=7.0.1"></script>

  <script src="/blog/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/blog/js/src/affix.js?v=7.0.1"></script>

  <script src="/blog/js/src/schemes/pisces.js?v=7.0.1"></script>



  
  <script src="/blog/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/blog/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/blog/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
